package com.hyy.demo.helloworld;

import org.squirrelframework.foundation.fsm.Condition;
import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory;
import org.squirrelframework.foundation.fsm.UntypedStateMachine;
import org.squirrelframework.foundation.fsm.UntypedStateMachineBuilder;
import org.squirrelframework.foundation.fsm.annotation.StateMachineParameters;
import org.squirrelframework.foundation.fsm.annotation.Transit;
import org.squirrelframework.foundation.fsm.annotation.Transitions;
import org.squirrelframework.foundation.fsm.impl.AbstractUntypedStateMachine;

/**
 * Created by hyygavin on 2017/12/11.
 */
@Transitions({
        @Transit(from="A", to="B", on="toB", callMethod="fromAToB"),
        @Transit(from="B", to="C", on="toC"),
        @Transit(from="C", to="D", on="toD")
})
@StateMachineParameters(stateType=String.class, eventType=TestEvent.class, contextType=Integer.class)
class UntypedStateMachineSample extends AbstractUntypedStateMachine {
    // No need to specify constructor anymore since 0.2.9
    // protected UntypedStateMachineSample(ImmutableUntypedState initialState,
    //  Map<Object, ImmutableUntypedState> states) {
    //    super(initialState, states);
    // }

    protected void fromAToB(String from, String to, TestEvent event, Integer context) {
        // transition action still type safe ...
    }

    protected void transitFromDToAOntoA(String from, String to, TestEvent event, Integer context) {
        // transition action still type safe ...
    }

    public static void main(String[] args) {
        UntypedStateMachineBuilder builder = StateMachineBuilderFactory.create(
                UntypedStateMachineSample.class);
        // state machine builder not type safe anymore
        builder.externalTransition().from("D").to("A").on(TestEvent.toA).when(new Condition1());
        builder.externalTransition().from("D").to("AA").on(TestEvent.toA).when(new Condition<Object>() {
            public boolean isSatisfied(Object o) {
                int i = Integer.valueOf(o.toString());
                System.out.println(i);
                return i>2;
            }

            public String name() {
                return null;
            }
        });


        UntypedStateMachine fsm = builder.newStateMachine("A");
        fsm.start();
        fsm.fire(TestEvent.toB);
        fsm.fire(TestEvent.toC);
        fsm.fire(TestEvent.toD);
        System.out.println(fsm.getCurrentState());
        fsm.fire(TestEvent.toA,10);
        System.out.println(fsm.getCurrentState());

    }
}
